import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

// 引入了路由所映射的组件
import login from "@/views/login.vue";
import index from "@/views/index.vue";
import welcome from "@/views/welcome.vue";
import postList from "@/views/posts/postList.vue";
import postPublic from "@/views/posts/postPublic.vue";

// 配值路由
const router = new VueRouter({
  routes: [
    {
      path: "/",
      redirect: { name: "index" },
    },
    {
      name: "login",
      path: "/login",
      component: login,
    },
    {
      name: "index",
      path: "/index",
      component: index,
      // 重定向写在children外
      redirect:{name: "welcome"},
      //放置嵌套路由
      children: [
        {
          name: "welcome",
          path: "welcome",
          component: welcome,
        },
        {
          name: "postList",
          path: "postList",
          component: postList,
        },
        {
          name: "postPublic",
          path: "postPublic",
          component: postPublic,
        },
      ],
    },
  ],
});

// 导航守卫/路由拦截
// 如果用户要去登录页以外的页面，没有token不能进入
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    let token = localStorage.getItem("news_back_token");
    if (token) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
